<template>
  <div style="padding:20px;">
        <el-button type="primary" v-if="!isExpandAll" size="mini" @click="toggleRowExpansion">展开</el-button>
        <el-button type="info"  v-if="isExpandAll" size="mini" @click="toggleRowExpansion">收起</el-button>
        <el-button type="danger"  size="mini" @click="batchDelete">批量删除</el-button>
        <el-tree :data="data" :props="defaultProps"
                ref="tree"
                 show-checkbox
                 @check-change ="checkChange"
                 node-key="value"
                 :default-expanded-keys="expandedKeys"

                 v-if="refreshTable"
                 :expand-on-click-node ="false"
                 :default-expand-all = "isExpandAll"
                 @node-click="handleNodeClick"
        >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>

              <span style="margin-left:20px;">
                <el-button
                  v-if="node.level<5"
                  type="text"
                  size="mini"
                  icon="el-icon-plus"
                  @click="() => append( node, data)">
                  添加
                </el-button>
                <el-button
                  v-if="node.level!=1"
                  type="text"
                  size="mini"
                  icon="el-icon-edit"
                  @click="() => edit( node, data)">
                  修改
                </el-button>
                <el-button
                  v-if ="node.childNodes.length==0"
                  type="text"
                  size="mini"
                  icon="el-icon-delete"
                  @click="() => remove(node, data)">
                  删除
                </el-button>
              </span>
            </span>
        </el-tree>

        <!-- 添加或修改增值保障对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="地区名称" prop="areaName">
              <el-input v-model="form.areaName" placeholder="请输入地区名称" />
            </el-form-item>
            <el-form-item label="地区代号" prop="areaCode">
              <el-input v-model="form.areaCode"  placeholder="请输入地区代号" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </el-dialog>
  </div>
</template>

<script>
import {delBaseArea, getTreeData, addBaseArea, updateBaseArea} from "@/api/webshop/BaseArea";
export default {
  name: "Tree",
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      data: [],
      // 是否全部展开
      isExpandAll:false,
      refreshTable: true, //重新渲染表格的状态
      expandedKeys:[],

      title : "",
      open : false,
      form : {},
      rules: {
        areaName: [
          { required: true, message: "地区名称", trigger: "blur" }
        ],
        areaCode: [
          { required: true, message: "地区代号", trigger: "blur" }
        ]
      },
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    getTreeData(){
      getTreeData().then(resp=>{
        this.data = resp.data
      })
    },
    handleNodeClick(data) {
      // console.log(data)

    },
    append(node, data){
      console.log("add",node, data)
      this.open = true;
      this.title = `${ data.label } : 添加地区`
      this.form = {
        areaName: "",
        areaCode: "",
        areaParId: data.value,
        areaLevel: data.lev + 1
      }
    },
    edit(node, data){
      console.log("edit",node, data)
      this.open = true;
      this.title = `修改地区`
      this.form = {
        areaId: data.value,
        areaName: data.label,
        areaCode: data.code,
        areaParId: node.parent.data.value,
        areaLevel: data.lev
      }
    },
    remove(node, data){
      console.log("del",node, data)
      this.$modal.confirm('确认要删除信息吗?').then(function() {
        // 我要干什么
        return delBaseArea(data.value)

      }).then((resp) => {
        // 成功了 回调
        console.log(resp)
        if (resp.code == 200) {
          this.$modal.msgSuccess("删除成功");
          this.getTreeData();
          console.log( node.parent.data.value )
          this.expandedKeys = [ node.parent.data.value ]
        }
      }).catch(() => {});
    },
    // 全部展开/折叠
    toggleRowExpansion() {

      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },

    checkChange(node, data, check, indeterminate){
      // console.log( node, data, check, indeterminate )
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      // console.log( checkedNodes )
    },
    batchDelete(){
      let checkedNodes = this.$refs.tree.getCheckedNodes();
      if( checkedNodes.length == 0 ){
        this.$modal.msgWarning("请先选择要删除的节点")
        return;
      }

      this.$modal.confirm('确认要删除这些信息吗?').then(function() {
        console.log( "checkedNodes:", checkedNodes.length)
        let ids = []
        checkedNodes.forEach( item => {
          console.log( "item:", item )
          if(item.children ==  null ){
            console.log( " item.value:",  item.value )
            ids.push( item.value )
          }
        })
        console.log( ids )
        return delBaseArea(ids.join(","))

      }).then((resp) => {
        if (resp.code == 200) {
          this.$modal.msgSuccess("删除成功");
          this.getTreeData();
          // this.toggleRowExpansion()
          // this.expandedKeys = [ node.parent.data.value ]
        }
      }).catch(() => {});
    },
    submitForm(){
      console.log( this.form )
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.areaId != null) {
            updateBaseArea(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getTreeData();
              this.expandedKeys = [ this.form.areaParId ]
            });
          } else {
            addBaseArea(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getTreeData();
              this.expandedKeys = [ this.form.areaParId ]
            });
          }
        }
      })
    },
  }
}
</script>


<style scoped lang="scss">
//.custom-tree-node {
//  flex: 1;
//  display: flex;
//  align-items: center;
//  justify-content: space-between;
//  font-size: 14px;
//  padding-right: 8px;
//}
</style>
